<?php
/**
 * 对日期检查
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/6/14
 * @copyright PanxSoft Inc.
 */
namespace App\Rules;

use App\Services\Locale\Language;
use Carbon\Carbon;
use Illuminate\Contracts\Validation\Rule;

/**
 * Class DateBetween
 *
 * @test
 *
 * @package App\Rules
 */
class DateBetween implements Rule
{
    const VALIDATION_LOCALE_KEY = 'validation.date_between';

    /**
     * @var string
     */
    protected $attribute;

    /**
     * @var Carbon
     */
    private $start_at;

    /**
     * @var Carbon
     */
    private $end_at;

    /**
     * Create a new rule instance.
     *
     * @param $start_at
     * @param $end_at
     */
    public function __construct($start_at, $end_at)
    {
        $this->start_at = new Carbon($start_at);
        $this->end_at = new Carbon($end_at);
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string $attribute
     * @param  mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->attribute = $attribute;

        if (! strtotime($value)) return false;

        $time = new Carbon($value);

        return $this->start_at->lte($time) && $this->end_at->gte($time);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        // find locale string
        $attr_name = $this->normalizeAttributeName();

        return trans(self::VALIDATION_LOCALE_KEY, [
            'attribute' => $attr_name,
            'start' => $this->start_at,
            'end' => $this->end_at,
        ]);
    }

    /**
     * @return array|\Illuminate\Contracts\Translation\Translator|null|string
     */
    private function normalizeAttributeName()
    {
        $trans_key = "validation.attributes.{$this->attribute}";
        $attr_name = trans($trans_key);

        // if no locale, use attribute name as default
        if ($attr_name === $trans_key) {
            $attr_name = $this->attribute;
        }

        return $attr_name;
    }
}
